package com.hellobike.haxing.modules.order.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hellobike.haxing.common.annotation.AutoLog;
import com.hellobike.haxing.common.constant.CacheConstant;
import com.hellobike.haxing.common.system.base.controller.BaseController;
import com.hellobike.haxing.common.system.query.QueryGenerator;
import com.hellobike.haxing.common.util.RedisUtil;
import com.hellobike.haxing.common.vo.Result;
import com.hellobike.haxing.modules.order.constant.OrderConstants;
import com.hellobike.haxing.modules.order.entity.MonthReward;
import com.hellobike.haxing.modules.order.entity.MonthRewardDetail;
import com.hellobike.haxing.modules.order.entity.OrderShopReward;
import com.hellobike.haxing.modules.order.service.IMonthRewardDetailService;
import com.hellobike.haxing.modules.order.service.IMonthRewardService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
* @Description: 月度达成奖励项设置
* @Author: haxing-boot
* @Date:   2020-01-08
* @Version: V1.0
*/
@RestController
@RequestMapping("/order/monthReward")
@Slf4j
public class MonthRewardController extends BaseController<MonthReward, IMonthRewardService> {
    @Autowired
    private IMonthRewardService monthRewardService;

    @Autowired
    private IMonthRewardDetailService monthRewardDetailService;

    @Autowired
    private RedisUtil redisUtil;

   /**
    * 分页列表查询
    *
    * @param monthReward
    * @param pageNo
    * @param pageSize
    * @param req
    * @return
    */
   @AutoLog(value = "首页广告弹框管理-分页列表查询")
   @GetMapping(value = "/list")
   public Result<?> queryPageList(MonthReward monthReward,
                                  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                  HttpServletRequest req) {
       QueryWrapper<MonthReward> queryWrapper = QueryGenerator.initQueryWrapper(monthReward, req.getParameterMap());
       Page<MonthReward> page = new Page<MonthReward>(pageNo, pageSize);
       IPage<MonthReward> pageList = monthRewardService.page(page, queryWrapper);
       return Result.ok(pageList);
   }

   /**
    * 添加
    * @param monthReward
    * @return
    */
   @AutoLog(value = "首页广告弹框管理-添加",operateType=2)
   @PostMapping(value = "/add")
   public Result<?> add(@RequestBody MonthReward monthReward) {
       monthRewardService.save(monthReward);
       return Result.ok("添加成功！");
   }

   /**
    *  编辑
    * @param monthReward
    * @return
    */
   @AutoLog(value = "首页广告弹框管理-编辑",operateType=3)
   @PutMapping(value = "/edit")
   public Result<?> edit(@RequestBody MonthReward monthReward) {
//       MonthReward result = monthRewardService.getOne(new QueryWrapper<MonthReward>().lambda().eq(MonthReward::getDeleted, 0)
//               .orderByDesc(MonthReward::getId).last("limit 1"));
//       if (result == null) {
//           monthRewardService.saveInfo(monthReward);
//       } else {
//           monthReward.setId(result.getId());
//           monthRewardService.updateInfo(monthReward);
//       }
       if (monthReward.getId() != null) {
           monthRewardService.updateInfo(monthReward);
       } else {
           monthRewardService.saveInfo(monthReward);
       }
       return Result.ok("编辑成功!");
   }

    /**
     * 通过id删除
     * @param id
     * @return
     */
    @AutoLog(value = "首页icon管理-删除",operateType=4)
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name="id",required=true) Long id) {
        monthRewardService.removeById(id);
        redisUtil.del(CacheConstant.OPERATE_ICON_LIST);
        return Result.ok("删除成功!");
    }

    /**
     *  批量删除
     * @param ids
     * @return
     */
    @AutoLog(value = "首页icon管理-批量删除",operateType=4)
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
        this.monthRewardService.removeByIds(Arrays.asList(ids.split(",")).stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList()));
        redisUtil.del(CacheConstant.OPERATE_ICON_LIST);
        return Result.ok("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name="id",required=true) Long id) {
        MonthReward monthReward = monthRewardService.getById(id);
        if(monthReward==null) {
            return Result.error("未找到对应数据");
        }
        return Result.ok(monthReward);
    }

    @GetMapping(value = "/queryRewardInfo")
    public Result<?> queryRewardInfo() {
        MonthReward monthReward = monthRewardService.getOne(new QueryWrapper<MonthReward>().lambda().eq(MonthReward::getDeleted, 0)
                .orderByDesc(MonthReward::getId).last("limit 1"));
        if(monthReward == null){
            return Result.error("未找到对应数据");
        }

        /** 查询奖励 **/
        LambdaQueryWrapper<MonthRewardDetail> queryWrapper = new QueryWrapper<MonthRewardDetail>().lambda();
        Date now = new Date();
        queryWrapper.eq(MonthRewardDetail::getDeleted, OrderConstants.DEL_FLAG_0);
        queryWrapper.eq(MonthRewardDetail::getMonthRewardId, monthReward.getId());
        queryWrapper.orderByAsc(MonthRewardDetail::getLevel);
        // 检索活动
        List<MonthRewardDetail> detailList = monthRewardDetailService.list(queryWrapper);
        if(!CollectionUtils.isEmpty(detailList)){
            if(detailList.size() >= 1){
                monthReward.setStepOneAmount(detailList.get(0).getAmount());
                monthReward.setStepOneReward(detailList.get(0).getRewardAmount());
            }
            if(detailList.size() >= 2){
                monthReward.setStepTwoAmount(detailList.get(1).getAmount());
                monthReward.setStepTwoReward(detailList.get(1).getRewardAmount());
            }
            if(detailList.size() >= 3){
                monthReward.setStepThreeAmount(detailList.get(2).getAmount());
                monthReward.setStepThreeReward(detailList.get(2).getRewardAmount());
            }
            if(detailList.size() >= 4){
                monthReward.setStepFourAmount(detailList.get(3).getAmount());
                monthReward.setStepFourReward(detailList.get(3).getRewardAmount());
            }
            if(detailList.size() >= 5){
                monthReward.setStepFiveAmount(detailList.get(4).getAmount());
                monthReward.setStepFiveReward(detailList.get(4).getRewardAmount());
            }
        }

        return Result.ok(monthReward);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param monthReward
     */
    @AutoLog(value = "首页icon管理-导出excel",operateType=6)
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, MonthReward monthReward) {
        return super.exportXls(request, monthReward, MonthReward.class, "icon管理");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @AutoLog(value = "首页icon管理-导入excel",operateType=5)
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, MonthReward.class);
    }

}
